$(document).ready(function () {

    // 标记为已读的功能
    $(".toggle-btn").on('click', function () {
        var $item = $(this);
        var notificationId = $item.data("notification-id");
        let parent = $item.parent().parent();
        if (parent.hasClass('unread')) {
            parent.removeClass('unread').addClass('read')
            $item.text("标为未读")
                .removeClass('is-danger is-outlined')
            parent.find(".status-icon")
                .addClass('read')
                .empty()
                .append('<i class="fas fa-check"></i>')
            noticeStatus(notificationId, 1, () => {
                noticeCount();
            })
        } else if (parent.hasClass('read')) {
            parent.removeClass('read').addClass('unread')
            $item.text("标为已读")
                .addClass('is-danger is-outlined')
            parent.find(".status-icon")
                .removeClass('read')
                .empty()
                .append('<span class="count">1</span>')
            noticeStatus(notificationId, 0, () => {
                noticeCount();
            })
        }

    })
});

function toArticleAndComment(notificationId, username, articleId, commentId) {
    console.log(`当前跳转的文章 => /${username}/${articleId}  => ${commentId}`)

    // 发送请求给后台重置状态
    noticeStatus(notificationId, 1, () => {
        window.location.href = `/question/${username}/${articleId}.html#commentId-${commentId}`;
    })

}

function noticeStatus(notificationId, status, callback) {
    $.ajax({
        url: `/notice/${notificationId}/${status}`,
        type: 'PUT',
        success: function (res) {
            if (res.code === 200) {
                callback()
            }
        },
        error: function (err) {
            // 确保错误处理与服务器响应结构相匹配
            showErrorToast(err);
        }
    });
}


function noticeCount() {
    let $userNotice = $("#user-notice");
    let $unreadNotice = $("#user-notice-unread");
    $.ajax({
        url: '/notice/unread',
        type: 'GET',
        success: function (res) {
            if (res.code === 200) {
                if (res.data === 0) {
                    $userNotice.empty().append('通知')
                } else {
                    if (!$userNotice.find('.status-icon').length > 0) {
                        $userNotice.empty().append(`
                        通知
                        <div class="status-icon">
                            <span id="user-notice-unread" class="count">${res.data}</span>
                        </div>
                        `)
                    } else {
                        $unreadNotice.text(res.data);
                    }
                }
            }
        },
        error: function (xhr, status, error) {

        }
    });
}
